package net.esj.basic.utils.algorithm;

import java.util.NoSuchElementException;

import net.esj.basic.core.engine.util.RandomUtils;

/**
 * 不可重复随机概率栈，根据先后进入的rate随机选取，当选取后会移出队列
 * 
 * @author Administrator
 *
 */
public class UnrepeatableNormalAlgorithm extends AbstractAlgorithm{

	@Override
	void calc() {
	}

	@Override
	public AlgoEntity pop() {
		
		if(getItems().length<=0){
			return null;
		}
		
		int sum = 0;
		for(int i=0;i<getItems().length;i++){
			sum += getItems()[i].getRate();
		}
		
		final int rnd = RandomUtils.get(sum);
		int i=0;
		int dm = 0;
		for(;;){
			AlgoEntity ae = getItems()[i];
			if(ae==null)
				throw new NoSuchElementException();
			i++;
			dm += ae.getRate();
			if(dm<rnd){
				continue;
			}else{
				remove(ae);
				return ae;
			}
		}
	}

}
